package threadDemo;

//交替答应ABCD    输入n次
public class VolatileWaitNotifyDemo {
    private int n;
    private volatile int flag = 1;

    //构造方法实现循环次数
    public VolatileWaitNotifyDemo(int count) {
        this.n = count;
    }

    public static void main(String[] args) throws InterruptedException {
        VolatileWaitNotifyDemo demo = new VolatileWaitNotifyDemo(5);
        new Thread(() -> {
            try {
                demo.print("a", 1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                demo.print("b", 2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                demo.print("c", 0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public synchronized void print(String str, int num) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            while (flag % 3 != num) this.wait();
            System.out.print(str);
            flag += 1;
            this.notifyAll();
        }
    }
}
